<script lang="ts" setup>
import tzLoading from '@/components/tz-loading.vue'
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import { ref } from 'vue'
import { ElMessage } from 'element-plus'

const toast = (message: string, type: 'success' | 'warning' | 'error' | 'info' = 'success') => {
  ElMessage({ message, type })
}


const appStore = useAppStore()


const tableData = ref([])





const handlePositiveClick = (row) => {
  tProjectControllerDelbyid(row.id).then(res => {
    toast('删除成功')
    getData()
  })

}

const dialogVisible = ref(false)
const openDialog = () => {
  dialogType.value = 'add'
  dialogVisible.value = true
}
const openEditDialog = (row) => {
  dialogType.value = 'edit'
  rowID.value = row.id
  Object.keys(ruleForm).forEach(v => {
    ruleForm[v] = row[v]
  })
  ruleForm.equipmentid = row.tequipments.map(v => {
    return {
      value: v.id
    }
  })





  dialogVisible.value = true
}


const dialogType = ref('add')
const rowID = ref('')
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({

  name: '',
  equipmentid: [], //设备id
  fzremail: '', //负责人邮箱
  fzrname: '', //负责人姓名
  fzrphone: '', //负责人手机

  description: '', //备注
  name1: '', //参数一名称
  name2: '',
  name3: '',
  name4: '',
  value1: '',
  value2: '',
  value3: '',
  value4: '',


  jyhytime: '', //建议换油时间
  jztime: '', //油加注时间
  brand: '',//油品牌名称
  noname: '',//油牌号
  rongliang: '',//容量
})

// 数据字段对话框相关
const dataFieldDialogVisible = ref(false)
const currentProjectId = ref('')
const dataFieldForm = ref([])
const password = ref('')

const openDataFieldDialog = (row) => {
  // tProjectControllerSelfieldbyid
  // tProjectControllerupdatezd  
  tProjectControllerSelfieldbyid(row.id).then(res => {
    console.log(res)
    dataFieldForm.value = res.result
  })
  currentProjectId.value = row.id
  password.value = '' // 清空口令输入框
  dataFieldDialogVisible.value = true
}

const updateDataField = () => {
  // 校验口令是否为空
  if (!password.value) {
    ElMessage.error('请输入口令')
    return
  }
  
  // 过滤出 zt 为 1 的字段，并返回 zdname 的集合
  const updatedFields = dataFieldForm.value
    .filter(field => field.zt == 1)
    .map(field => field.zdname)

  let Q = {
    "kl": password.value, // 使用用户输入的口令
    projectid: currentProjectId.value,
    zd: updatedFields
  }
  tProjectControllerupdatezd(Q).then(res => {
    toast('修改成功')
    dataFieldDialogVisible.value = false
    password.value = '' // 清空口令输入框
  }).catch(err => {
    console.error('修改失败', err)
    toast('修改失败，请重试')
  })
}

const rules = reactive<FormRules<RuleForm>>({
  name: [
    { required: true, message: '请输入项目名称', trigger: 'blur' },
  ],
})


const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {

      let Q = {
        ...ruleForm
      }
      let T = []
      ruleForm.equipmentid.forEach(v => {
        if (v.value) {
          T.push(v.value)
        }
      })
      Q.equipmentid = T


      if (dialogType.value == 'add') {
        tProjectControllerInsert(Q).then(res => {
          console.log(res)
          getData()
          toast('新增成功')
        })
      } else {
        Q.id = rowID.value
        tProjectControllerUpdate(Q).then(res => {
          getData()
          toast('修改成功')
        })
      }


      dialogVisible.value = false
    } else {
      console.log('error submit!', fields)
    }
  })
}


const closeFn = () => {
  Object.keys(ruleForm).forEach(v => {
    ruleForm[v] = ''
  })
  ruleForm.equipmentid = []
  rowID.value = ''
}


const loading = ref(true)


// search
const searchForm = reactive({
  projectNumber: "",
  deviceName: '',
  deviceNumber: ''
})


const transducerOptions = ref([])


const getOptions = () => {
  tEquipmentControllerSelbypage({
    size: 1000,
    index: 1,
    equipmentid: ''
  }).then(res => {
    transducerOptions.value = res.result.map(v => {
      return {
        value: v.id,
        label: v.equipmentid,
      }
    })
  })
}

getOptions()


const getData = () => {
  loading.value = true
  tProjectControllerSellist().then(res => {
    console.log(res)
    tableData.value = res.result
  }).finally(() => {
    loading.value = false
  })
}

getData()



const addList = () => {
  ruleForm.equipmentid.push({
    value: ''
  })
}



// 新增检测
const dialogTableVisible = ref(false)
const gridData = ref([])
const opneId = ref(null)
const projectName = ref('')
const openDetection = (row) => {
  dialogTableVisible.value = true
  opneId.value = row.id
  projectName.value = row.name
  PId.value = row.id
  getDetectionData()
}



const getDetectionData = () => {
  tProjectControllerSeljcxbzbyid(opneId.value).then(res => {
    console.log(res, 'res')
    gridData.value = res.result
  })
}

const innerVisible = ref(false)
const DetectiondialogType = ref('add')

const DetectioruleFormRef = ref<FormInstance>()
const PId = ref(null)
const DetectioruleForm = reactive({
  bz: '',
  name: '',
  projectid: '',
  id: ''
})
const Detectiorules = reactive<FormRules<RuleForm>>({
  name: [
    { required: true, message: '请输入检测项名称', trigger: 'blur' },
  ],
  bz: [
    { required: true, message: '请输入检测项标准', trigger: 'blur' },
  ],
})


const openDetectionDialog = (row) => {
  Object.keys(DetectioruleForm).forEach(v => {
    DetectioruleForm[v] = row[v]
  })

  innerVisible.value = true
  DetectiondialogType.value = 'edit'
}

const openDialogDetectio = () => {
  DetectiondialogType.value = 'add'
  innerVisible.value = true
}


const DetectionClickDel = (row) => {
  tProjectControllerDelbzbyid(row.id).then(res => {
    toast('删除成功')
    getDetectionData()
  })
}

const submitFormDetectio = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {

      let Q = {
        ...DetectioruleForm
      }

      if (DetectiondialogType.value == 'add') {
        Q.projectid = PId.value
        tProjectControllerInsertbz(Q).then(res => {
          getDetectionData()
          toast('新增成功')
        })
      } else {
        tProjectControllerUpdatebz(Q).then(res => {
          getDetectionData()
          toast('修改成功')
        })
      }


      innerVisible.value = false
    } else {
      console.log('error submit!', fields)
    }
  })
}

const closeFnDetection = () => {
  Object.keys(DetectioruleForm).forEach(v => {
    DetectioruleForm[v] = ''
  })
}

</script>

<template>
  <tzLoading v-if="loading"></tzLoading>

  <div class="flex flex-col flex-1 overflow-auto" v-else>

    <el-dialog v-model="dialogTableVisible" :title="projectName" width="600px">


      <el-button @click="openDialogDetectio" class="w-[90px] mb-[20px] flex justify-center items-center"
        color="#009757">
        <span class="text-[16px] font-medium text-white">新增</span>
      </el-button>


      <el-table :data="gridData">
        <el-table-column property="name" label="检测项名称" width="200" />

        <el-table-column property="bz" label="检测项标准" width="150" />

        <el-table-column label="操作" width="200">
          <template #default="scope">
            <div>
              <el-button class="" size="small" type="warning" @click="openDetectionDialog(scope.row)">
                <span>修改</span>
              </el-button>


              <el-popconfirm title=" 确定要删除吗？" @confirm="DetectionClickDel(scope.row)">
                <template #reference>
                  <el-button size="small" type="danger">
                    <span class="text-white">删除</span>
                  </el-button>
                </template>
              </el-popconfirm>


              <!-- <n-popconfirm @positive-click="DetectionClickDel(scope.row)">
                <template #trigger>
                  <el-button size="small" type="danger">
                    <span class="text-white">删除</span>
                  </el-button>
                </template>
                确定要删除吗？
              </n-popconfirm> -->
            </div>



          </template>
        </el-table-column>
      </el-table>


      <el-dialog v-model="innerVisible" width="500" :title="DetectiondialogType == 'add' ? '新增' : '修改'" append-to-body
        @close="closeFnDetection" destroy-on-close>

        <el-form ref="DetectioruleFormRef" :model="DetectioruleForm" :rules="Detectiorules" label-width="auto"
          style="width: 100%;" class="demo-ruleForm flex-1" status-icon>

          <el-row :gutter="20">

            <el-col :span="24">
              <el-form-item label="检测项名称" prop="name">
                <el-input v-model="DetectioruleForm.name" />
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="检测项标准" prop="bz">
                <el-input v-model="DetectioruleForm.bz" />
              </el-form-item>

            </el-col>

          </el-row>

        </el-form>



        <template #footer>
          <div class="dialog-footer">
            <el-button @click="innerVisible = false">取消</el-button>
            <el-button type="primary" @click="submitFormDetectio(DetectioruleFormRef)">
              <span class="text-white">确定</span>
            </el-button>
          </div>
        </template>


      </el-dialog>


    </el-dialog>


    <div class="h-[13%]"></div>
    <div class="px-[25px] flex">



      <!-- <el-form-item label="项目号" class="mr-[40px]">
        <el-input v-model="searchForm.projectNumber" />
      </el-form-item>


      <el-form-item label="设备类型" class="mr-[40px]">
        <el-input v-model="searchForm.deviceNumber" />
      </el-form-item> -->
      <!-- 
      <el-button class="w-[90px] ml-auto  flex justify-center items-center" color="#0c9bc8">
        <span class="text-[16px] font-medium text-white">查询</span>
      </el-button> -->


      <el-button @click="openDialog" class="w-[90px]  flex justify-center items-center" color="#009757">
        <span class="text-[16px] font-medium text-white">新增</span>
      </el-button>

    </div>
    <div class="flex-1 p-[25px] overflow-auto">

      <el-table fit :data="tableData" style="width: 100%;overflow: auto;">

        <el-table-column prop="name" label="项目号" />
        <!-- <el-table-column prop="fzremail" label="负责人邮箱" />
        <el-table-column prop="fzrname" label="负责人姓名" />
        <el-table-column prop="fzrphone" label="负责人手机" /> -->


        <el-table-column prop="tequipments
" label="设备" min-width="200px">
          <template #default="scope">
            <div class="flex gap-[10px]">
              <el-tag v-for="(i, n) in scope.row.tequipments" type="info" :key="n">{{ i.equipmentid }}</el-tag>
            </div>
          </template>
        </el-table-column>


        <el-table-column prop="brand" label="油品牌名称" />
        <el-table-column prop="noname" label="油牌号" />
        <el-table-column prop="rongliang" label="容量" />
        <el-table-column prop="jyhytime" label="建议换油时间" />
        <el-table-column prop="jztime" label="油加注时间" />











        <!-- <el-table-column prop="description" label="备注" /> -->















        <el-table-column label="操作" width="320">
          <template #default="scope">
            <div>

              <el-button class="" size="small" type="info" @click="openDetection(scope.row)">
                <span>检测标准</span>
              </el-button>


              <el-button class="" size="small" type="primary" @click="openDataFieldDialog(scope.row)">
                <span>数据字段</span>
              </el-button>

              <el-button class="" size="small" type="warning" @click="openEditDialog(scope.row)">
                <span>修改</span>
              </el-button>

              <n-popconfirm @positive-click="handlePositiveClick(scope.row)">
                <template #trigger>
                  <el-button size="small" type="danger">
                    <span class="text-white">删除</span>
                  </el-button>
                </template>
                确定要删除吗？
              </n-popconfirm>
            </div>



          </template>
        </el-table-column>

      </el-table>

    </div>
    <div class="h-[20px]"></div>

    <el-dialog v-model="dialogVisible" :title="dialogType == 'add' ? '新增项目' : '编辑项目'" width="600px" top="8vh"
      @close="closeFn" destroy-on-close>
      <div class="flex justify-center gap-[30px]">
        <div class="flex-1 flex flex-col items-center">


          <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="auto" style="width: 100%;"
            class="demo-ruleForm flex-1" status-icon>


            <el-row :gutter="20">



              <el-col :span="12">
                <el-form-item label="项目号" prop="name">
                  <el-input v-model="ruleForm.name" />
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="负责人邮箱" prop="fzremail">
                  <el-input v-model="ruleForm.fzremail" />
                </el-form-item>

              </el-col>
              <el-col :span="12">
                <el-form-item label="负责人姓名" prop="fzrname">
                  <el-input v-model="ruleForm.fzrname" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="负责人手机" prop="fzrphone">
                  <el-input v-model="ruleForm.fzrphone" />
                </el-form-item>
              </el-col>



              <el-col :span="24">
                <el-form-item label="备注" prop="description">
                  <el-input autosize type="textarea" v-model="ruleForm.description" />
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="参数一名称" prop="name1">
                  <el-input v-model="ruleForm.name1" />
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="参数一值" prop="value1">
                  <el-input v-model="ruleForm.value1" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="参数二名称" prop="name2">
                  <el-input v-model="ruleForm.name2" />
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="参数二值" prop="value2">
                  <el-input v-model="ruleForm.value2" />
                </el-form-item>
              </el-col>




              <el-col :span="12">
                <el-form-item label="参数三名称" prop="name3">
                  <el-input v-model="ruleForm.name3" />
                </el-form-item>
              </el-col>


              <el-col :span="12">
                <el-form-item label="参数三值" prop="value3">
                  <el-input v-model="ruleForm.value3" />
                </el-form-item>
              </el-col>


              <el-col :span="12">
                <el-form-item label="参数四名称" prop="name4">
                  <el-input v-model="ruleForm.name4" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="参数四值" prop="value4">
                  <el-input v-model="ruleForm.value4" />
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="油品牌名称" prop="brand">
                  <el-input v-model="ruleForm.brand" />
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="油牌号" prop="noname">
                  <el-input v-model="ruleForm.noname" />
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="容量" prop="rongliang">
                  <el-input v-model="ruleForm.rongliang" />
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="建议换油时间" prop="jyhytime">
                  <el-input v-model="ruleForm.jyhytime" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="油加注时间" prop="jztime">
                  <el-input v-model="ruleForm.jztime" />
                </el-form-item>
              </el-col>






            </el-row>





























            <template v-for="(item, index) in ruleForm.equipmentid">
              <el-form-item :label="'设备' + (index + 1)">
                <el-select v-model="item.value" placeholder="请选择设备" filterable>
                  <el-option v-for="(i, n) in transducerOptions" :key="n" :label="i.label" :value="i.value" />
                </el-select>
              </el-form-item>
            </template>

            <el-button @click="addList" class="w-[190px]  flex justify-center items-center" color="#009757">
              <span class="text-[16px] font-medium text-white">新增设备</span>
            </el-button>










          </el-form>




        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            <span class="text-white">确定</span>
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 数据字段对话框 -->
    <el-dialog v-model="dataFieldDialogVisible" title="数据字段" width="400px" top="8vh">
      <div>

        <div v-if="dataFieldForm.length > 0">
          <el-form-item v-for="(field, index) in dataFieldForm" :key="index" :label="field.zdname" label-width="100px">
            <el-switch v-model="field.zt" :active-value="1" :inactive-value="0" active-text="展示" inactive-text="不展示" />
          </el-form-item>
          
          <!-- 口令输入框 -->
          <el-form-item label="口令" label-width="100px" class="mt-4">
            <el-input v-model="password" placeholder="请输入口令" show-password />
          </el-form-item>
        </div>

        <div v-else class="text-center text-gray-500 py-8">
          暂无数据字段
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dataFieldDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="updateDataField" :disabled="dataFieldForm.length === 0">
            确定修改
          </el-button>
        </div>
      </template>
    </el-dialog>


  </div>
</template>

<style scoped>
:deep(.el-table__row) {
  background-color: #f3fdf1;
}

:deep(th>.el-table__cell) {
  background-color: #0f914c;
}

:deep(.el-table th.el-table__cell) {
  background-color: #0e904c;
}


:deep(.el-table th.el-table__cell .cell) {
  color: #fff;
}
</style>
